<?php
class Order {
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth) {
        $this->conn = $conn;
        $this->auth = $auth;
    }

    /**
     * 创建新订单（支持多员工）
     */
    public function create(): void {
        try {
            // 验证用户登录状态
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            // 获取输入数据
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input === null) {
                throw new Exception("无效的JSON数据", 400);
            }

            // 数据验证
            $errors = $this->validateOrderData($input);
            if (!empty($errors)) {
                throw new Exception(implode(", ", $errors), 400);
            }

            // 验证员工信息（如果提供了员工ID）
            if (!empty($input['member_id'])) {
                $this->validateMembers($input['member_id']);
            }

            // 准备订单数据
            $orderData = $this->prepareOrderData($input, $userId);

            // 创建订单
            $result = $this->saveOrder($orderData);

            // 如果订金大于0，创建付款记录
            if ($orderData['deposit'] > 0) {
                $this->createPaymentRecord([
                    'order_id' => $result['order_id'],
                    'amount' => $orderData['deposit'],
                    'payment_method' => $orderData['payment_method'],
                    'note' => '订金支付',
                    'creator_id' => $userId
                ]);
            }

            // 返回成功响应
            echo json_encode([
                'code' => 200,
                'msg' => '订单创建成功',
                'data' => $result
            ]);

        } catch (PDOException $e) {
            error_log("Database error: " . $e->getMessage());
            throw new Exception("数据库操作失败: " . $e->getMessage(), 500);
        } catch (Exception $e) {
            error_log("Order creation error: " . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 验证多个员工信息
     */
    private function validateMembers(string $memberIds): void {
        $memberIdArray = explode(',', $memberIds);
        $memberIdArray = array_filter(array_map('trim', $memberIdArray));
        
        if (empty($memberIdArray)) {
            return;
        }

        // 构建IN查询参数
        $placeholders = implode(',', array_fill(0, count($memberIdArray), '?'));
        
        $stmt = $this->conn->prepare("
            SELECT id, username as name FROM users 
            WHERE id IN ($placeholders) AND status = 1
        ");
        $stmt->execute($memberIdArray);
        $validMembers = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 检查所有提供的ID是否都有效
        $validIds = array_column($validMembers, 'id');
        $invalidIds = array_diff($memberIdArray, $validIds);
        
        if (!empty($invalidIds)) {
            throw new Exception("以下员工ID不存在或已禁用: " . implode(',', $invalidIds), 400);
        }
    }

    private function validateOrderData(array $data): array {
        $errors = [];

        // 必填字段验证
        $requiredFields = [
            'customerName' => '客户姓名',
            'type' => '服务类型',
            'startDate' => '开始日期',
            'endDate' => '结束日期'
        ];

        foreach ($requiredFields as $field => $name) {
            if (empty($data[$field])) {
                $errors[] = "{$name}不能为空";
            }
        }

        // 日期验证
        $startDate = strtotime($data['startDate'] ?? '');
        $endDate = strtotime($data['endDate'] ?? '');
        
        if (!$startDate) {
            $errors[] = "开始日期格式不正确";
        }
        
        if (!$endDate) {
            $errors[] = "结束日期格式不正确";
        }
        
        if ($startDate && $endDate && $endDate < $startDate) {
            $errors[] = "结束日期不能早于开始日期";
        }

        return $errors;
    }

    private function prepareOrderData(array $input, int $userId): array {
        // 处理多员工信息
        $memberIds = null;
        $memberNames = null;
        
        if (!empty($input['member_id'])) {
            $memberIds = $input['member_id'];
            
            // 如果前端没有提供memberName，则从数据库查询
            if (empty($input['member'])) {
                $memberIdArray = explode(',', $input['member_id']);
                $placeholders = implode(',', array_fill(0, count($memberIdArray), '?'));
                
                $stmt = $this->conn->prepare("
                    SELECT username as name FROM users 
                    WHERE id IN ($placeholders) AND status = 1
                ");
                $stmt->execute($memberIdArray);
                $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                $memberNames = implode('、', array_column($members, 'name'));
            } else {
                $memberNames = $input['member'];
            }
        }

        return [
            'order_number' => $this->generateOrderNumber(),
            'customer_name' => $input['customerName'],
            'phone' => $input['phone'],
            'type' => $input['type'],
            'start_date' => $input['startDate'],
            'end_date' => $input['endDate'],
            'channel' => $input['channel'] ?? '线上',
            'deposit' => floatval($input['deposit'] ?? 0),
            'final_payment' => floatval($input['finalPayment'] ?? 0),
            'total_amount' => floatval($input['deposit'] ?? 0) + floatval($input['finalPayment'] ?? 0),
            'payment_method' => $input['paymentMethod'] ?? '微信',
            'status' => '待处理',
            'creator_id' => $userId,
            'member_id' => $memberIds,
            'member_name' => $memberNames,
            'note' => $input['note'] ?? '',
            'create_time' => date('Y-m-d H:i:s')
        ];
    }

    private function saveOrder(array $orderData): array {
        $this->conn->beginTransaction();
        
        try {
            $stmt = $this->conn->prepare("
                INSERT INTO orders (
                    order_number, customer_name, phone, type, 
                    start_date, end_date, channel, deposit, 
                    final_payment, total_amount, payment_method, 
                    status, creator_id, member_id, member_name, note, create_time
                ) VALUES (
                    :order_number, :customer_name, :phone, :type,
                    :start_date, :end_date, :channel, :deposit,
                    :final_payment, :total_amount, :payment_method,
                    :status, :creator_id, :member_id, :member_name, :note, :create_time
                )
            ");

            $stmt->execute($orderData);

            $orderId = $this->conn->lastInsertId();
            $this->conn->commit();

            return [
                'order_id' => $orderId,
                'order_number' => $orderData['order_number'],
                'total_amount' => $orderData['total_amount'],
                'member_id' => $orderData['member_id'],
                'member_name' => $orderData['member_name'],
                'note' => $orderData['note']
            ];

        } catch (PDOException $e) {
            $this->conn->rollBack();
            throw new Exception("数据库操作失败: " . $e->getMessage(), 500);
        }
    }

    private function generateOrderNumber(): string {
        $prefix = 'ORD';
        $date = date('Ymd');
        $random = substr(strtoupper(bin2hex(random_bytes(3))), 0, 6);
        return $prefix . $date . $random;
    }

    /**
     * 更新订单信息（支持多员工）
     */
    public function update(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }
            
            $data = json_decode(file_get_contents('php://input'), true);
            
            // 验证必填字段
            if (empty($data['id'])) {
                throw new Exception("缺少订单ID", 400);
            }

            // 检查订单是否存在且属于当前用户
            $stmt = $this->conn->prepare("
                SELECT id FROM orders 
                WHERE id = :id AND creator_id = :creator_id
                LIMIT 1
            ");
            $stmt->execute([
                ':id' => $data['id'],
                ':creator_id' => $userId
            ]);
            if (!$stmt->fetch()) {
                throw new Exception("订单不存在或无权操作", 404);
            }

            // 处理member_id为空字符串的情况
            if (isset($data['member_id']) && $data['member_id'] === '') {
                $data['member_id'] = null;
                $data['member_name'] = null;
            }

            // 验证员工信息（如果提供了有效的员工ID）
            if (!empty($data['memberId']) || !empty($data['member_id'])) {
                $memberIds = $data['memberId'] ?? $data['member_id'];
                $this->validateMembers($memberIds);
            }

            // 构建更新字段
            $updateFields = ["update_time = :update_time"];
            $params = [
                ':id' => $data['id'],
                ':update_time' => date('Y-m-d H:i:s')
            ];

            // 可更新字段
            $allowedFields = [
                'customer_name', 'phone', 'type', 'start_date', 'end_date',
                'channel', 'deposit', 'final_payment', 'payment_method', 'status',
                'member_id', 'member_name', 'note'
            ];

            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $updateFields[] = "{$field} = :{$field}";
                    $params[":{$field}"] = $data[$field] === '' ? null : $data[$field];
                }
            }

            // 如果更新了员工ID但没有提供员工姓名，自动获取
            if (isset($data['member_id']) && (!isset($data['member_name']) || $data['member_name'] === '')) {
                if (!empty($data['member_id'])) {
                    $memberIdArray = explode(',', $data['member_id']);
                    $placeholders = implode(',', array_fill(0, count($memberIdArray), '?'));
                    
                    $stmt = $this->conn->prepare("
                        SELECT username as name FROM users 
                        WHERE id IN ($placeholders) AND status = 1
                    ");
                    $stmt->execute($memberIdArray);
                    $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    if ($members) {
                        $updateFields[] = "member_name = :member_name";
                        $params[':member_name'] = implode('、', array_column($members, 'name'));
                    }
                } else {
                    $updateFields[] = "member_name = NULL";
                }
            }

            // 如果更新了金额相关字段，重新计算总金额
            if (isset($data['deposit']) || isset($data['final_payment'])) {
                $deposit = $data['deposit'] ?? 0;
                $finalPayment = $data['final_payment'] ?? 0;
                $updateFields[] = "total_amount = :total_amount";
                $params[':total_amount'] = $deposit + $finalPayment;
            }

            if (count($updateFields) <= 1) {
                throw new Exception("没有可更新的字段", 400);
            }

            // 执行更新
            $sql = "UPDATE orders SET " . implode(', ', $updateFields) . " 
                    WHERE id = :id AND creator_id = :creator_id";
            $params[':creator_id'] = $userId;
            
            $stmt = $this->conn->prepare($sql);
            
            if (!$stmt->execute($params)) {
                $errorInfo = $stmt->errorInfo();
                throw new Exception("更新订单信息失败: " . ($errorInfo[2] ?? '未知错误'), 500);
            }

            // 返回成功信息
            echo json_encode([
                'code' => 200,
                'msg' => '更新成功'
            ]);

        } catch (Exception $e) {
         // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
         echo json_encode([
             'code' => $e->getCode() ?: 500,
             'message' => $e->getMessage()
         ]);
      }
    }

    /**
     * 获取订单列表
     */
    public function list(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            // 获取分页参数
            $page = max(1, intval($_GET['page'] ?? 1));
            $pageSize = min(50, max(1, intval($_GET['pageSize'] ?? 20)));
            $offset = ($page - 1) * $pageSize;

            // 构建查询条件
            $where = ["creator_id = :creator_id"];
            $params = [':creator_id' => $userId];
            
            // 添加筛选条件
            if (!empty($_GET['keyword'])) {
                $keyword = '%' . $_GET['keyword'] . '%';
                $where[] = "(customer_name LIKE :keyword OR phone LIKE :keyword OR order_number LIKE :keyword OR note LIKE :keyword)";
                $params[':keyword'] = $keyword;
            }

            if (!empty($_GET['queryDate'])) {
                $where[] = ":query_date BETWEEN start_date AND end_date";
                $params[':query_date'] = $_GET['queryDate'];
            }

            if (!empty($_GET['type'])) {
                $where[] = "type = :type";
                $params[':type'] = $_GET['type'];
            }

            if (!empty($_GET['status'])) {
                $where[] = "status = :status";
                $params[':status'] = $_GET['status'];
            }

            if (!empty($_GET['has_material'])) {
                $where[] = "has_material = :has_material";
                $params[':has_material'] = $_GET['has_material'];
            }

            if (!empty($_GET['startDate'])) {
                $where[] = "start_date >= :start_date";
                $params[':start_date'] = $_GET['startDate'];
            }

            if (!empty($_GET['endDate'])) {
                $where[] = "end_date <= :end_date";
                $params[':end_date'] = $_GET['endDate'];
            }

            // 按员工筛选
            if (!empty($_GET['memberId'])) {
                $where[] = "FIND_IN_SET(:member_id, member_id) > 0";
                $params[':member_id'] = $_GET['memberId'];
            }

            // 按备注筛选
            if (!empty($_GET['note'])) {
                $where[] = "note LIKE :note";
                $params[':note'] = '%' . $_GET['note'] . '%';
            }

            $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

            // 查询总数
            $countStmt = $this->conn->prepare("SELECT COUNT(*) FROM orders {$whereClause}");
            $countStmt->execute($params);
            $total = (int)$countStmt->fetchColumn();

            // 查询数据
            $query = "
                SELECT 
                    id, order_number, customer_name, phone, type, 
                    start_date, end_date, channel, 
                    CAST(deposit AS DECIMAL(10,2)) as deposit,
                    CAST(final_payment AS DECIMAL(10,2)) as final_payment,
                    CAST(total_amount AS DECIMAL(10,2)) as total_amount,
                    payment_method, status, create_time, update_time, has_material,
                    member_id, member_name, note
                FROM orders
                {$whereClause}
                ORDER BY id DESC
                LIMIT :offset, :limit
            ";
            
            $stmt = $this->conn->prepare($query);
            
            // 绑定分页参数
            $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
            $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
            
            // 绑定其他参数
            foreach ($params as $key => $value) {
                $stmt->bindValue($key, $value);
            }
            
            $stmt->execute();
            $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // 返回列表数据
            echo json_encode([
                'code' => 200,
                'data' => [
                    'list' => $list,
                    'pagination' => [
                        'total' => $total,
                        'page' => $page,
                        'pageSize' => $pageSize,
                        'totalPages' => ceil($total / $pageSize)
                    ]
                ]
            ]);

        } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'message' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取订单详情
     */
    public function detail(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            if (empty($_GET['id'])) {
                throw new Exception("缺少订单ID参数", 400);
            }

            $orderId = filter_var($_GET['id'], FILTER_VALIDATE_INT);
            if ($orderId === false || $orderId <= 0) {
                throw new Exception("订单ID必须是正整数", 400);
            }

            // 查询订单基本信息
            $stmt = $this->conn->prepare("
                SELECT 
                    id, order_number, customer_name, phone, type, 
                    start_date, end_date, channel, 
                    CAST(deposit AS DECIMAL(10,2)) as deposit,
                    CAST(final_payment AS DECIMAL(10,2)) as final_payment,
                    CAST(total_amount AS DECIMAL(10,2)) as total_amount,
                    payment_method, status, has_material, create_time, update_time,
                    member_id, member_name, note
                FROM orders
                WHERE id = :id AND creator_id = :creator_id
                LIMIT 1
            ");
            
            $stmt->execute([
                ':id' => $orderId,
                ':creator_id' => $userId
            ]);
            
            $order = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$order) {
                throw new Exception("订单不存在或无权查看", 404);
            }

            // 查询关联的素材信息
            $materialStmt = $this->conn->prepare("
                SELECT m_link, upload_time 
                FROM materials 
                WHERE order_id = :order_id
                ORDER BY id DESC
                LIMIT 1
            ");
            $materialStmt->execute([':order_id' => $orderId]);
            $material = $materialStmt->fetch(PDO::FETCH_ASSOC);

            // 查询付款记录
            $paymentStmt = $this->conn->prepare("
                SELECT 
                    id, 
                    CAST(amount AS DECIMAL(10,2)) as amount,
                    payment_method,
                    note,
                    creator_id,
                    create_time
                FROM payment_records
                WHERE order_id = :order_id
                ORDER BY create_time DESC
            ");
            $paymentStmt->execute([':order_id' => $orderId]);
            $payments = $paymentStmt->fetchAll(PDO::FETCH_ASSOC);

            // 合并订单和素材数据
            if ($material) {
                $order['m_link'] = $material['m_link'];
                $order['material_upload_time'] = $material['upload_time'];
            } else {
                $order['m_link'] = null;
                $order['material_upload_time'] = null;
            }

            // 格式化数据
            $order['deposit'] = floatval($order['deposit']);
            $order['final_payment'] = floatval($order['final_payment']);
            $order['total_amount'] = floatval($order['total_amount']);
            $order['start_date'] = date('Y-m-d', strtotime($order['start_date']));
            $order['end_date'] = date('Y-m-d', strtotime($order['end_date']));
            $order['create_time'] = date('Y-m-d H:i:s', strtotime($order['create_time']));
            $order['update_time'] = $order['update_time'] ? date('Y-m-d H:i:s', strtotime($order['update_time'])) : null;
            $order['material_upload_time'] = $order['material_upload_time'] ? date('Y-m-d H:i:s', strtotime($order['material_upload_time'])) : null;
            $order['note'] = $order['note'] ?? '';
            $order['payments'] = $payments;

            echo json_encode([
                'code' => 200,
                'data' => $order
            ]);

        } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'message' => $e->getMessage()
            ]);
        }
    }

    /**
     * 删除订单
     */
    public function delete(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }
            
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (empty($data['id'])) {
                throw new Exception("缺少订单ID", 400);
            }

            $orderId = $data['id'];

            // 检查订单是否存在且属于当前用户
            $stmt = $this->conn->prepare("                SELECT id FROM orders 
                WHERE id = :id AND creator_id = :creator_id
                LIMIT 1
            ");
            $stmt->execute([
                ':id' => $orderId,
                ':creator_id' => $userId
            ]);
            if (!$stmt->fetch()) {
                throw new Exception("订单不存在或无权操作", 404);
            }

            // 开始事务
            $this->conn->beginTransaction();
            
            try {
                // 1. 先删除关联的付款记录
                $stmt = $this->conn->prepare("                    DELETE FROM payment_records 
                    WHERE order_id = :order_id
                ");
                $stmt->execute([':order_id' => $orderId]);
                
                // 2. 再删除关联的素材记录
                $stmt = $this->conn->prepare("                    DELETE FROM materials 
                    WHERE order_id = :order_id
                ");
                $stmt->execute([':order_id' => $orderId]);
                
                // 3. 最后删除订单记录
                $stmt = $this->conn->prepare("                    DELETE FROM orders 
                    WHERE id = :id AND creator_id = :creator_id
                ");
                
                if (!$stmt->execute([
                    ':id' => $orderId,
                    ':creator_id' => $userId
                ])) {
                    throw new Exception("删除订单失败", 500);
                }
                
                // 提交事务
                $this->conn->commit();
                
                echo json_encode([
                    'code' => 200,
                    'msg' => '删除成功'
                ]);
                
            } catch (Exception $e) {
                // 回滚事务
                $this->conn->rollBack();
                throw $e;
            }

        } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'message' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取员工列表
     */
    public function staffList(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            $stmt = $this->conn->prepare("
                SELECT 
                    id, 
                    username as name, 
                    position, 
                    mobile,
                    real_name,
                    email
                FROM users
                WHERE status = 1
                ORDER BY id DESC
            ");
            
            $stmt->execute();
            $staffList = $stmt->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode([
                'code' => 200,
                'data' => $staffList
            ]);

        } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'message' => $e->getMessage()
            ]);
        }
    }

    /**
     * 将订单状态设置为已完成
     */
    public function complete(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            // 获取输入数据
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input === null) {
                throw new Exception("无效的JSON数据", 400);
            }

            // 验证必填字段
            if (empty($input['id'])) {
                throw new Exception("缺少订单ID", 400);
            }

            $orderId = $input['id'];

            // 检查订单是否存在且属于当前用户
            $stmt = $this->conn->prepare("
                SELECT id FROM orders 
                WHERE id = :id AND creator_id = :creator_id
                LIMIT 1
            ");
            $stmt->execute([
                ':id' => $orderId,
                ':creator_id' => $userId
            ]);
            
            if (!$stmt->fetch()) {
                throw new Exception("订单不存在或无权操作", 404);
            }

            // 更新订单状态为"已完成"
            $stmt = $this->conn->prepare("
                UPDATE orders 
                SET status = '已完成', 
                    update_time = :update_time
                WHERE id = :id AND creator_id = :creator_id
            ");
            
            $result = $stmt->execute([
                ':id' => $orderId,
                ':creator_id' => $userId,
                ':update_time' => date('Y-m-d H:i:s')
            ]);

            if (!$result) {
                throw new Exception("更新订单状态失败", 500);
            }

            // 返回成功响应
            echo json_encode([
                'code' => 200,
                'msg' => '订单状态已更新为已完成'
            ]);

        } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'message' => $e->getMessage()
            ]);
        }
    }

    /**
     * 设置订单状态
     */
    public function setStatus(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            // 获取输入数据
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input === null) {
                throw new Exception("无效的JSON数据", 400);
            }

            // 验证必填字段
            if (empty($input['id'])) {
                throw new Exception("缺少订单ID", 400);
            }
            if (empty($input['status'])) {
                throw new Exception("缺少状态参数", 400);
            }

            $orderId = $input['id'];
            $status = $input['status'];

            // 定义允许的状态值
            $allowedStatuses = ['待处理', '进行中', '已完成', '已取消', '已退款'];
            if (!in_array($status, $allowedStatuses)) {
                throw new Exception("无效的状态值", 400);
            }

            // 检查订单是否存在且属于当前用户
            $stmt = $this->conn->prepare("
                SELECT id FROM orders 
                WHERE id = :id AND creator_id = :creator_id
                LIMIT 1
            ");
            $stmt->execute([
                ':id' => $orderId,
                ':creator_id' => $userId
            ]);
            
            if (!$stmt->fetch()) {
                throw new Exception("订单不存在或无权操作", 404);
            }

            // 更新订单状态
            $stmt = $this->conn->prepare("
                UPDATE orders 
                SET status = :status, 
                    update_time = :update_time
                WHERE id = :id AND creator_id = :creator_id
            ");
            
            $result = $stmt->execute([
                ':id' => $orderId,
                ':status' => $status,
                ':creator_id' => $userId,
                ':update_time' => date('Y-m-d H:i:s')
            ]);

            if (!$result) {
                throw new Exception("更新订单状态失败", 500);
            }

            // 返回成功响应
            echo json_encode([
                'code' => 200,
                'msg' => '订单状态已更新',
                'data' => [
                    'id' => $orderId,
                    'status' => $status
                ]
            ]);

        } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'message' => $e->getMessage()
            ]);
        }
    }

    /**
     * 创建付款记录
     */
    private function createPaymentRecord(array $paymentData): void {
        $stmt = $this->conn->prepare("
            INSERT INTO payment_records (
                order_id, amount, payment_method, note, creator_id, create_time
            ) VALUES (
                :order_id, :amount, :payment_method, :note, :creator_id, :create_time
            )
        ");
        
        $stmt->execute([
            ':order_id' => $paymentData['order_id'],
            ':amount' => $paymentData['amount'],
            ':payment_method' => $paymentData['payment_method'],
            ':note' => $paymentData['note'],
            ':creator_id' => $paymentData['creator_id'],
            ':create_time' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * 添加付款记录并更新订单金额
     */
    public function addPayment(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            // 获取输入数据
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input === null) {
                throw new Exception("无效的JSON数据", 400);
            }

            // 验证必填字段
            if (empty($input['order_id'])) {
                throw new Exception("缺少订单ID", 400);
            }
            if (empty($input['amount']) || $input['amount'] <= 0) {
                throw new Exception("付款金额必须大于0", 400);
            }
            if (empty($input['payment_method'])) {
                throw new Exception("请选择付款方式", 400);
            }

            $orderId = $input['order_id'];
            $amount = floatval($input['amount']);
            $paymentMethod = $input['payment_method'];
            $note = $input['note'] ?? '';

            // 检查订单是否存在且属于当前用户
            $stmt = $this->conn->prepare("
                SELECT id, deposit, final_payment, total_amount 
                FROM orders 
                WHERE id = :id AND creator_id = :creator_id
                LIMIT 1
            ");
            $stmt->execute([
                ':id' => $orderId,
                ':creator_id' => $userId
            ]);
            
            $order = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$order) {
                throw new Exception("订单不存在或无权操作", 404);
            }

            // 计算剩余尾款
            $remainingPayment = $order['final_payment'] - ($order['total_amount'] - $order['deposit']);

            // 检查付款金额是否超过剩余尾款
            if ($amount > $remainingPayment) {
                throw new Exception("付款金额不能超过剩余尾款: " . $remainingPayment, 400);
            }

            $this->conn->beginTransaction();

            try {
                // 创建付款记录
                $this->createPaymentRecord([
                    'order_id' => $orderId,
                    'amount' => $amount,
                    'payment_method' => $paymentMethod,
                    'note' => $note,
                    'creator_id' => $userId
                ]);

                // 更新订单订金金额
                $newDeposit = $order['deposit'] + $amount;
                $stmt = $this->conn->prepare("
                    UPDATE orders 
                    SET deposit = :deposit, 
                        update_time = :update_time
                    WHERE id = :id
                ");
                
                $stmt->execute([
                    ':id' => $orderId,
                    ':deposit' => $newDeposit,
                    ':update_time' => date('Y-m-d H:i:s')
                ]);

                $this->conn->commit();

                // 返回成功响应
                echo json_encode([
                    'code' => 200,
                    'msg' => '付款记录添加成功',
                    'data' => [
                        'order_id' => $orderId,
                        'new_deposit' => $newDeposit,
                        'remaining_payment' => $remainingPayment - $amount
                    ]
                ]);

            } catch (Exception $e) {
                $this->conn->rollBack();
                throw $e;
            }

        } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'message' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取订单的付款记录
     */
    public function getPaymentRecords(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            if (empty($_GET['order_id'])) {
                throw new Exception("缺少订单ID参数", 400);
            }

            $orderId = filter_var($_GET['order_id'], FILTER_VALIDATE_INT);
            if ($orderId === false || $orderId <= 0) {
                throw new Exception("订单ID必须是正整数", 400);
            }

            // 检查订单是否存在且属于当前用户
            $stmt = $this->conn->prepare("
                SELECT id FROM orders 
                WHERE id = :id AND creator_id = :creator_id
                LIMIT 1
            ");
            $stmt->execute([
                ':id' => $orderId,
                ':creator_id' => $userId
            ]);
            
            if (!$stmt->fetch()) {
                throw new Exception("订单不存在或无权查看", 404);
            }

            // 查询付款记录
            $stmt = $this->conn->prepare("
                SELECT 
                    id, 
                    CAST(amount AS DECIMAL(10,2)) as amount,
                    payment_method,
                    note,
                    creator_id,
                    create_time
                FROM payment_records
                WHERE order_id = :order_id
                ORDER BY create_time DESC
            ");
            
            $stmt->execute([':order_id' => $orderId]);
            $records = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // 格式化金额
            foreach ($records as &$record) {
                $record['amount'] = floatval($record['amount']);
                $record['create_time'] = date('Y-m-d H:i:s', strtotime($record['create_time']));
            }

            echo json_encode([
                'code' => 200,
                'data' => $records
            ]);

        } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'message' => $e->getMessage()
            ]);
        }
    }
    /**
 * 按月统计订单数据
 * @method GET
 * @route /order/statsByMonth
 * @param string $month 格式为 'YYYY-MM'
 */
public function statsByMonth(): void {
    try {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        // 获取查询参数
        $month = $_GET['month'] ?? date('Y-m');
        
        // 验证月份格式
        if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
            throw new Exception("月份格式不正确，应为YYYY-MM", 400);
        }

        // 计算月份的开始和结束日期
        $startDate = date('Y-m-01', strtotime($month));
        $endDate = date('Y-m-t', strtotime($month));

        // 查询本月统计数据
        $stmt = $this->conn->prepare("
            SELECT 
                COUNT(*) as order_count,
                COALESCE(SUM(deposit), 0) as total_deposit,
                COALESCE(SUM(total_amount), 0) as total_amount,
                COALESCE(SUM(total_amount - deposit), 0) as total_final_payment
            FROM orders
            WHERE creator_id = :creator_id
            AND start_date BETWEEN :start_date AND :end_date
        ");
        $stmt->execute([
            ':creator_id' => $userId,
            ':start_date' => $startDate,
            ':end_date' => $endDate
        ]);
        $stats = $stmt->fetch(PDO::FETCH_ASSOC);

        // 查询本月订单明细（不分页）
        $stmt = $this->conn->prepare("
            SELECT 
                id as order_id,
                customer_name,
                type,
                start_date as order_date,
                CAST(deposit AS DECIMAL(10,2)) as deposit,
                CAST(total_amount - deposit AS DECIMAL(10,2)) as final_payment,
                CAST(total_amount AS DECIMAL(10,2)) as total_amount
            FROM orders
            WHERE creator_id = :creator_id
            AND start_date BETWEEN :start_date AND :end_date
            ORDER BY start_date DESC
        ");
        $stmt->execute([
            ':creator_id' => $userId,
            ':start_date' => $startDate,
            ':end_date' => $endDate
        ]);
        $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 格式化金额字段
        foreach ($orders as &$order) {
            $order['deposit'] = floatval($order['deposit']);
            $order['final_payment'] = floatval($order['final_payment']);
            $order['total_amount'] = floatval($order['total_amount']);
        }

        // 返回结果
        echo json_encode([
            'code' => 200,
            'data' => [
                'stats' => [
                    'month' => $month,
                    'order_count' => (int)$stats['order_count'],
                    'total_deposit' => floatval($stats['total_deposit']),
                    'total_amount' => floatval($stats['total_amount']),
                    'total_final_payment' => floatval($stats['total_final_payment'])
                ],
                'orders' => $orders
            ]
        ]);

    } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'message' => $e->getMessage()
        ]);
    }
}
}